import { NavigateService } from './../../../service/navigate.service';
import { MdDialog, MdDialogRef, MdDialogConfig } from "@angular/material";
import { RemarkService } from './../../../component/primeng/remark/remark.module';
import { TableService } from './../../../service/table.service';
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { OrderTable, OrderTableService } from "./orderTable";
import { Table } from "../../../model/clerkDataContext";

export class OrderConfirmService {
    private tmp: OrderConfirm;
    static Current: OrderConfirmService = new OrderConfirmService();
    private tableSvr: TableService;
    dialogRef: MdDialogRef<OrderConfirm>;
    config: MdDialogConfig = {
        disableClose: false,
        width: '100%',
        position: {
            top: '0',
            bottom: '0',
            left: '0',
            right: '0'
        }
    }
    constructor() {
    }
    Regist(tmp: OrderConfirm, tableSvr: TableService) {
        this.tmp = tmp;
        this.tableSvr = tableSvr;
    }
    async Open(dialog: MdDialog, tableId: string, commonRemarks?: string[]) {
        this.dialogRef = dialog.open(OrderConfirm, this.config);
        this.tmp.tableInfo = await this.tableSvr.GetTableInfo(tableId);
        this.tmp.ex_tables = await this.getOtherTables(this.tmp.tableInfo);
        this.tmp.selectTables = [];
        this.tmp.selectTables.push(this.tmp.tableInfo);
        this.tmp.visible = true;
        this.tmp.remark = null;
        if (commonRemarks) {
            this.tmp.commonRemarks = commonRemarks;
        } else {
            this.tmp.commonRemarks = null;
        }
        return new Promise((resolve, reject) => {
            this.dialogRef.afterClosed().subscribe(data => {
                this.dialogRef = null;
                resolve(data);
            });
        });
    }

    private async getOtherTables(tableInfo) {
        let ex_tabs = [];
        if (tableInfo.tableParty && tableInfo.tableParty.tableGroupId) {
            let tbs = await this.tableSvr.GetGroupTables(tableInfo.tableParty.tableGroupId);
            tbs.forEach(x => {
                if (x.id != tableInfo.id) ex_tabs.push(x);
            });
        }
        return ex_tabs;
    }
}


@Component({
    //moduleId: module.id,
    selector: 'div[order-confirm]',
    template: `
        <md-dialog-content fxLayout="column" fxFlex="100%">
            <header class="app-header noshrink">
                <span id="dialog-back-btn" class="i-arrow-back margin-l header-icon" (click)="cancel()"></span>
                <span fxFlex="100%" class="margin-l-xs">确认下单</span>
            </header>
            <div tabindex="0" autofocus fxLayout="column" fxFlex="100%">
                <div *ngIf="tableInfo && tableInfo.tableParty && tableInfo.tableParty.tableGroupId" fxLayout="column" class="padding-l-s padding-r-s">
                    <div class="text-s v-gap noshrink" fxLayout="row">
                        <span fxFlex="100%">选择下单台桌</span>
                        <md-checkbox class="noshrink md-primary" [checked]="allCheck()" [(ngModel)]="chooseAll" (change)="selectAllTables($event.checked)">
                            <span>全部选择</span>
                        </md-checkbox>
                    </div>
                    <div class="v-scroll" fxLayout="row" fxLayoutWrap="wrap" fxLayoutAlign="space-between start">
                        <div class="order-confirm-table v-gap text-s" fxFlex="48%" fxLayout="row" fxLayoutAlign="center center" *ngFor="let table of ex_tables" (click)="selectTable(table)" [ngClass]="{'bgcolor-primary color-white': table.selected}">
                            <span>{{table.name}}</span>
                        </div>
                    </div>
                </div>

                <div class="order-confirm-textarea padding-s noshrink">
                    <textarea class="pct100 text-s padding-xs" placeholder="请输入备注信息" [(ngModel)]="remark"></textarea>
                    <div *ngIf="commonRemarks && commonRemarks.length" fxLayout="row" fxLayoutWrap="wrap">
                        <div class="v-gap tag-plus" *ngFor="let comRemark of commonRemarks" (click)="onSelectComRemark(comRemark)">
                            <span>{{comRemark.content}}</span>
                        </div>
                    </div>
                </div>
            </div>
            <button class="pct100 bgcolor-accent noshrink color-white normal-btn text-m" md-button (click)="onOrder()">确认下单</button>
        </md-dialog-content>
    `,
    styleUrls: ['../order.component.scss']
})
export class OrderConfirm {
    visible: boolean;
    tableInfo: any;
    showSelectTable: boolean;
    selectTables = [];
    chooseAll: boolean = false;
    ex_tables = [];
    remark: string;
    commonRemarks: string[];
    constructor(
        private tableSvr: TableService,
        private dialog: MdDialog,
        public dialogRef: MdDialogRef<OrderConfirm>,
        private navSvr: NavigateService
    ) {
        OrderConfirmService.Current.Regist(this, tableSvr);
        this.navSvr.registGoBack(this.goBack);
    }

    goBack() {
        let backBtn = document.getElementById("dialog-back-btn");
        if (backBtn) {
            backBtn.click();
        }
    }

    async onOrder() {
        //并台情况下，下单到所有台桌
        if (this.chooseAll) {
            this.selectTables = [];
            this.selectTables.push(this.tableInfo);
            this.selectTables = this.selectTables.concat(this.ex_tables);
        } else {
            this.selectTables = [];
            this.selectTables.push(this.tableInfo);
            let selTables = this.getSelectedTables();
            this.selectTables = this.selectTables.concat(selTables);
        }
        let returnData = {
            remark: this.remark,
            selectTables: this.selectTables
        }
        this.dialogRef.close(returnData);
    }

    /**
     * 选择某个台桌
     */
    selectTable(table) {
        table.selected = !table.selected;
    }

    /**
     * 判断是否全选
     */
    allCheck() {
        if (!this.ex_tables || !this.ex_tables.length) return false;
        return this.ex_tables.every(table => { return table.selected }) ? true : false;
    }
    /**
     * 全选
     */
    selectAllTables(selected: boolean) {
        this.ex_tables.forEach(t => t.selected = selected);
    }
    /**
     * 选择通用备注
     * @param comRemark 备注信息 
     */
    onSelectComRemark(comRemark) {
        if (this.remark && this.remark.length) {
            this.remark += ("," + comRemark.content);
        } else {
            this.remark = comRemark.content;
        }
    }
    /**
     * 获取选中的台桌
     */
    getSelectedTables() {
        let selectedTables = [];
        this.ex_tables.forEach(element => {
            if (element.selected) {
                selectedTables.push(element);
            }
        });
        return selectedTables;
    }

    cancel() {
        this.dialogRef.close(null);
    }
}